package com.start.workflow.core.listener;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.delegate.event.impl.ActivitiProcessStartedEventImpl;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * activiti 全局监听器
 */
@Slf4j
@Component
public class StartGlobalActActivityListener implements ActivitiEventListener, Serializable {


    /**
     * Called when an event has been fired
     *
     * @param event the event
     */
    @Override
    public void onEvent(ActivitiEvent event) {
        ActivitiEventType type = event.getType();
        log.info("流程全局事件" + type);
        switch (type) {
            case TASK_CREATED://任务创建
                ActivitiEntityEventImpl entityEvent = (ActivitiEntityEventImpl) event;
                String processDefinitionId = entityEvent.getProcessDefinitionId();
                String processInstanceId = entityEvent.getProcessInstanceId();
                TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();
                log.info(String.format("流程定义id=%s 流程实例id=%s 任务id=%s", processDefinitionId, processInstanceId, taskEntity.getId()));
                StartGlobalUserTaskHandler.getInstance().addTask(taskEntity);
                break;
            case PROCESS_COMPLETED:// 流程完成
                StartGlobalActProcessHandler.getInstance().processCompleted(event);
                break;

        }
    }

    /**
     * @return whether or not the current operation should fail when this listeners execution throws an exception.
     */
    @Override
    public boolean isFailOnException() {
        return false;
    }
}
